package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 使用递归，遍历整个三级分类（三层树）
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {

        List<CategoryEntity> entities = baseMapper.selectList(null);

        //找到所有的一级分类
        List<CategoryEntity> levelMenus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return levelMenus;
    }

    @Override
    public void removeMenuByIds(List<Long> list) {

        //TODO 检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(list);

    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
//        return (Long[]) parentPath.toArray();
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Transactional
    @Override
//    @CacheEvict(value = "category" ,key = "'getLevel1Categorys'")
/*    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatelogJson'")
    })*/
    @CacheEvict(value = "category",allEntries = true)
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    //每一个需要缓存的数据我们都来指定要放到哪个名字的缓存【缓存的分区（按照业务类型分）】
    //,key = "#root.method.name",unless="#result == null"
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)//代表当前方法的结果需要缓存，如果缓存中有响应的数据，方法不用调用，如果缓存中没有数据，会调用方法
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("你好。。。。。");
        long l = System.currentTimeMillis();
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        System.out.println("消耗时间：" + (System.currentTimeMillis() - l));
        return entities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {

        //1、加入缓存逻辑，缓存中存的数据是json字符串  json跨语言，跨平台兼容
        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(catalogJson)) {
            //2、缓存中没有，就去查询数据库
            System.out.println("缓存未命中，查询数据库");
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedissonLock();
            //3、查到的数据再放入缓存，将对象转为json放到缓存中
            String s = JSON.toJSONString(catalogJsonFromDb);
            stringRedisTemplate.opsForValue().set("catalogJson", s);
            return catalogJsonFromDb;
        }
        return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
    }

    public Map<String,List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock(){
        //1、锁的名字，锁的粒度，越细越快
        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();
        Map<String,List<Catelog2Vo>> dataFromDb;
        try{
            dataFromDb = getDataFromDb();
        }finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock05() {

        //1、占分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功");
            //加锁成功。。。执行业务
            //2、设置过期时间 必须和加锁是同步的，原子的
            Map<String, List<Catelog2Vo>> dataFromDb;

            try {
                dataFromDb = getDataFromDb();
            }finally {
                /**
                 * 获取值对比，对比成功删除  原子操作，lua脚本解锁
                 */
                //脚本 if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        } else {
            //加锁失败，重试
            System.out.println("获取分布式锁失败，等待重试");
            return getCatalogJsonFromDbWithRedisLock05();
        }
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock04() {

        //1、占分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if (lock) {
            //加锁成功。。。执行业务
            //2、设置过期时间 必须和加锁是同步的，原子的
            Map<String, List<Catelog2Vo>> dataFromDb = getDataFromDb();
            String lockValue = stringRedisTemplate.opsForValue().get("lock");
            if(uuid.equals(lockValue)){
                stringRedisTemplate.delete("lock");//删除锁
            }
            return dataFromDb;
        } else {
            //加锁失败，重试
            return getCatalogJsonFromDbWithRedisLock04();
        }
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock03() {

        //1、占分布式锁，去redis占坑
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "111",300,TimeUnit.SECONDS);
        if (lock) {
            //加锁成功。。。执行业务
            //2、设置过期时间 必须和加锁是同步的，原子的
            Map<String, List<Catelog2Vo>> dataFromDb = getDataFromDb();
            stringRedisTemplate.delete("lock");
            return dataFromDb;
        } else {
            //加锁失败，重试
            return getCatalogJsonFromDbWithRedisLock03();
        }
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock02() {

        //1、占分布式锁，去redis占坑
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "111");
        if (lock) {
            //加锁成功。。。执行业务
            //2、设置过期时间 为30秒
            stringRedisTemplate.expire("lock",30, TimeUnit.SECONDS);
            Map<String, List<Catelog2Vo>> dataFromDb = getDataFromDb();
            stringRedisTemplate.delete("lock");
            return dataFromDb;
        } else {
            //加锁失败，重试
            return getCatalogJsonFromDbWithRedisLock02();
        }
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock01() {

        //1、占分布式锁，去redis占坑
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "111");
        if (lock) {
            //加锁成功。。。执行业务
            Map<String, List<Catelog2Vo>> dataFromDb = getDataFromDb();
            stringRedisTemplate.delete("lock");
            return dataFromDb;
        } else {
            //加锁失败，重试
            return getCatalogJsonFromDbWithRedisLock01();
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {

        //得到锁以后，我们应该再去缓存中确定一次，如果没有才需要继续查询
        String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
        if (!StringUtils.isEmpty(catalogJson)) {
            //缓存不为空，直接返回
            return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }

        System.out.println("查询了数据库");
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1、查出所有一级分类
        List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);

        //2、封装数据
        Map<String, List<Catelog2Vo>> listMap = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());

            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(),
                            item.getName());
                    //1、找出当前二级分类的三级分类 并封装成vo
                    List<CategoryEntity> level3Catelog = getParentCid(selectList, item.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatelog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());

            }
            return catelog2Vos;
        }));
        return listMap;
    }


    private Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {

        synchronized (this) {
            //得到锁以后，我们应该再去缓存中确定一次，如果没有才需要继续查询
            String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
            if (!StringUtils.isEmpty(catalogJson)) {
                //缓存不为空，直接返回
                return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
            }
            List<CategoryEntity> selectList = baseMapper.selectList(null);

            //1、查出所有一级分类
            List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);

            //2、封装数据
            Map<String, List<Catelog2Vo>> listMap = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

                List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());

                List<Catelog2Vo> catelog2Vos = null;
                if (categoryEntities != null) {
                    catelog2Vos = categoryEntities.stream().map(item -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(),
                                item.getName());
                        //1、找出当前二级分类的三级分类 并封装成vo
                        List<CategoryEntity> level3Catelog = getParentCid(selectList, item.getCatId());
                        if (level3Catelog != null) {
                            List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                                Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return catelog3Vo;
                            }).collect(Collectors.toList());
                            catelog2Vo.setCatelog3List(collect);
                        }
                        return catelog2Vo;
                    }).collect(Collectors.toList());

                }
                return catelog2Vos;
            }));
            return listMap;
        }
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> list, Long parent_cid) {
        List<CategoryEntity> collect = list.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> entities) {

        //找到所有的一级分类
        List<CategoryEntity> children = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, entities));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }


}